package org.apache.zookeeper.recipes.lock;

import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * 参考地址：
 * http://chenkangxian.iteye.com/blog/1525807
 * 
 * @author zenghua233
 *
 */
public class MyDistributedLockTest {
	private WriteLock lock;
	private String lockPath = "/lock";
	private ZooKeeper zooKeeper;

	public MyDistributedLockTest(ZooKeeper zooKeeper) {
		this.zooKeeper = zooKeeper;
	}

	/**
	 * 获得锁
	 * 
	 * Author: chenkangxian
	 * 
	 * Last Modification Time: 2012-4-6
	 * 
	 * @return 获得锁是否成功
	 */
	public boolean lock() {
		lock = new WriteLock(zooKeeper, lockPath, null);
		try {
			while (true) {
				if (lock.lock()) {
					return true;
				}

			}
		} catch (KeeperException e) {
			e.printStackTrace();
			return false;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 解锁
	 * 
	 * Author: chenkangxian
	 * 
	 * Last Modification Time: 2012-4-6
	 * 
	 */
	public void unlock() {
		lock.unlock();
	}

	public static void main(String args[]) {

		try {
			Watcher wh = new Watcher() {
				public void process(org.apache.zookeeper.WatchedEvent event) {
					System.out.println(event.toString());
				}
			};

			ZooKeeper zooKeeper = new ZooKeeper("localhost:2181", 20000, wh);
			final MyDistributedLockTest distributedLock = new MyDistributedLockTest(zooKeeper);

			for (int i = 0; i < 100; i++) {
				Thread thread = new Thread(new Runnable() {

					@Override
					public void run() {
						if (distributedLock.lock()) {
							System.out.println("获得锁---------------");

						}

						distributedLock.unlock();

					}

				});
			}

			Thread.sleep(2000 * 1000);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}
